package com.yue.se.reflect;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Collections;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/9/8<br/>
 *
 * @author QiuYang
 */
public class PropertyDescriptorTest {

    public static void main(String[] args) throws Exception {
        PropertyDescriptorTest test = new PropertyDescriptorTest();
//        test.testPropertyDescriptor();
//        test.testConstructor();
        test.testArrayFelect();
    }

    public void testConstructor() throws Exception{
//        Arrays.asList(Collections.class.getDeclaredClasses()).forEach(c -> System.out.println(c.getName()));

        Class<Person> cls = Person.class;
        Constructor constructor = cls.getConstructor();
        System.out.println(constructor.toGenericString());

        Method method = cls.getMethod("getName", null);
        System.out.println(method.toGenericString());

        Field field = cls.getDeclaredField("name");

        System.out.println();

    }

    public void testPropertyDescriptor() throws Exception{
        Person person = new Person();
        System.out.println(person.getName());

        PropertyDescriptor propertyDes = new PropertyDescriptor("name", Person.class);
        Method getMethod = propertyDes.getReadMethod();
        Method setMethod = propertyDes.getWriteMethod();

        setMethod.invoke(person, "zhangsan");
        System.out.println(person.getName());

        Object obj = getMethod.invoke(person, null);
        System.out.println(obj);

        Method getOther = Person.class.getMethod("getUpperCaseName", null);
        Method setOther = Person.class.getMethod("setLowerCaseName", String.class);
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", getOther, setOther);
        System.out.println(propertyDescriptor.getReadMethod().invoke(person, null));
    }


    public void testArrayFelect() {
        int[] ia = {1,2,3};
        String[] sa = {"a","b","c"};

        printObject(ia);
        printObject(sa);
        printObject(Arrays.asList(sa));
    }

    private void printObject(Object obj) {
        Class cls = obj.getClass();
        if(cls.isArray()){
            int length = Array.getLength(obj);
            for(int i = 0;i < length;i++){
                System.out.print(Array.get(obj, i)+":"+i+"\t");
            }
            System.out.println();
        }else{
            System.out.println(obj);
        }
    }
}
